import { defineStore } from 'pinia'
import {ref} from "vue";
import user from '../apis/user';

export const useUserStore = defineStore('user', () => {
    const userInfo = ref({
      nickName: "",
      username: "",
      ttc:""
    })
    
    function updateUserInfo(data:any) {
      userInfo.value = data;
    }

    async function fetchUserInfo(){
      return new Promise((res,rej)=>{
        user.getUserInfo().then(ret=>{
          if(ret.code == 0){
            userInfo.value = ret.data;
            console.log('userInfo', userInfo.value);
            res(ret.data);
          }else{
            rej(new Error(ret.message));
          }
        }).catch(err=>{
          rej(err);
        })
      });
    }

    async function logout() {
      try {
        const ret = await user.logout();
        if(ret.code == 0){
          userInfo.value = {
            nickName: "",
            username: "",
            ttc:""
          };
          console.log('clear userInfo', userInfo.value);
        }
      } catch (error) {
        return error
      }
    }
  
    return { userInfo, updateUserInfo, fetchUserInfo, logout }
})